#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings



def BuildMapForm():
    Dict={}
    ExistingMapNameChoices=[]
    ExistingMapNameChoices.append(['-1', 'None'])
    ExistingMapNames=Map.objects.all().order_by('Name')
    for i in ExistingMapNames:
        ExistingMapNameChoices.append([i.id, str(i.Name)[:35]])
    Dict['UpdateIndicator']=forms.BooleanField()
    Dict['DeleteIndicator']=forms.BooleanField()
    Dict['NameExistingList']=forms.ChoiceField(ExistingMapNameChoices, required=False)
    Dict['Name']=forms.CharField(required=True, widget=forms.TextInput(attrs={'size':'20'})) 
    Dict['Content']=forms.CharField(required=True, widget=forms.widgets.Textarea(attrs={'rows':40, 'cols':120}))
    return Dict

def BuildMapTemplateForm():
    Dict={}
    ExistingMapTemplateNameChoices=[]
    ExistingMapTemplateNameChoices.append(['-1', 'None'])
    ExistingMapTemplateNames=MapTemplate.objects.all().order_by('Name')
    for i in ExistingMapTemplateNames:
        ExistingMapTemplateNameChoices.append([i.id, str(i.Name)[:35]])
    Dict['UpdateIndicator']=forms.BooleanField()
    Dict['DeleteIndicator']=forms.BooleanField()
    Dict['NameExistingList']=forms.ChoiceField(ExistingMapTemplateNameChoices, required=False)
    Dict['Name']=forms.CharField(required=True, widget=forms.TextInput(attrs={'size':'25'})) 
    Dict['Tag']=forms.CharField(required=True, widget=forms.TextInput(attrs={'size':'25'}))
    Dict['Content']=forms.CharField(required=True, widget=forms.widgets.Textarea(attrs={'rows':40, 'cols':120}))
    return Dict





def ProcessMapForm(form, UserName):
    try:
        UpdateIndicator=bool(form.data['UpdateIndicator'] == 'on')
    except:
        UpdateIndicator=False
    try:
        DeleteIndicator=bool(form.data['DeleteIndicator'] == 'on')
    except:
        DeleteIndicator=False
    try:
        Content=form.data['Content']
    except:
        Content=''
    if(UpdateIndicator):  #First typed in map name with any changes to data
        aMap=Map()
        aMap=aMap.GetOrCreate(Name=form.data['Name'], UserName=UserName, Content=Content)
    if(DeleteIndicator):
        ToDelete=Map.objects.filter(Name__exact=form.data['Name'])[0]
        if(ToDelete.id == int(form.data['NameExistingList'])):
            form.data['NameExistingList'] = -1
        ToDelete.delete()
        form.data['DeleteIndicator'] = False
        form.data['Content'] = ''
    try:
        Selectid=int(form.data['NameExistingList'])
    except:
        try:
            Selectid=Map.objects.filter(Name=form.data['Name'])[0].id
            form.data['NameExistingList']=Selectid
        except KeyError:
            Selectid=-1
            form.data['NameExistingList']=Selectid
    if(Selectid <> -1):  #Now select a New Map (if selected) and load its data into the form
        Selected=Map.objects.filter(id__exact=Selectid)[0]
        form.data['Name'] = Selected.Name
        form.data['Content'] = Selected.Content
    if(Selectid <> -1):
        MapFileName=Selected.GenerateMapFile(UserName, 'MapSetup')
    else:
        MapFileName = ''
        Selected=None
    if(Selected):    #This Layer Name is Used by OpenLayers to connect the the WMS Server, maybe a Javascript workaround can eliminate this code?
        LayerName=Selected.GetLayerName()
    else:
        LayerName = 'No Map Selected'
    return form, LayerName, MapFileName



def ProcessMapTemplateForm(form, UserName):
    try:
        UpdateIndicator=bool(form.data['UpdateIndicator'] == 'on')
    except:
        UpdateIndicator=False
    try:
        DeleteIndicator=bool(form.data['DeleteIndicator'] == 'on')
    except:
        DeleteIndicator=False
    try:
        Content=form.data['Content']
    except:
        Content=''
    try:
        Tag=form.data['Tag']
    except:
        Tag=''
    if(UpdateIndicator):  #First typed in map name with any changes to data
        aMapTemplate=MapTemplate()
        aMapTemplate=aMapTemplate.GetOrCreate(Name=form.data['Name'], UserName=UserName, Tag=Tag, Content=Content)
    if(DeleteIndicator):
        ToDelete=MapTemplate.objects.filter(Name=form.data['Name'])[0]
        if(ToDelete.id == int(form.data['NameExistingList'])):
            form.data['NameExistingList'] = -1
        ToDelete.delete()
        form.data['DeleteIndicator'] = False
        form.data['Content'] = ''
    try:
        Selectid=int(form.data['NameExistingList'])
    except:
        try:
            Selectid=MapTemplate.objects.filter(Name=form.data['Name'])[0].id
            form.data['NameExistingList']=Selectid
        except KeyError:
            Selectid=-1
            form.data['NameExistingList']=Selectid
    if(Selectid <> -1):  #Now select a New Map (if selected) and load its data into the form
        Selected=MapTemplate.objects.filter(id=Selectid)[0]
        form.data['Name'] = Selected.Name
        form.data['Content'] = Selected.Content
        form.data['Tag'] = Selected.Tag
    return form


